package indi.zhifa.core.common.web.aop;

import indi.zhifa.core.common.web.entity.ann.ZhiFaRestController;
import indi.zhifa.core.common.web.entity.response.RestResponse;
import indi.zhifa.core.common.web.handler.IResponseHandler;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.ArrayList;
import java.util.List;

@RestControllerAdvice(annotations ={ZhiFaRestController.class,ControllerAdvice.class})
public class GlobalRestfulResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    List<IResponseHandler> mResponseHandlers = new ArrayList<>();

//    @Value("${spring.profiles.active}")
//    String profile;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    protected Object _beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        for(IResponseHandler handler : mResponseHandlers){
            if(handler.match(body,returnType,selectedContentType,selectedConverterType,request,response)){
                return handler.beforeBodyWrite(body,returnType,selectedContentType,selectedConverterType,request,response);
            }
        }
        if ( body instanceof RestResponse){
            return body;
        }
        if( body instanceof String){
            return body;
        }
        return RestResponse.ok(body);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        Object rtn = _beforeBodyWrite(body,returnType,selectedContentType,selectedConverterType,request,response);
        for(IResponseHandler handler : mResponseHandlers){
            handler.endBodyWrite(body,returnType,selectedContentType,selectedConverterType,request,response);
        }
        return rtn;
    }

    public void addHandler(IResponseHandler pIResponseHandler){
        mResponseHandlers.add(pIResponseHandler);
    }
}
